package net.alan.modules.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.alan.common.utils.Base64;
import net.alan.common.utils.CompareUtil;
import net.alan.common.utils.IOUtils;
import net.alan.common.utils.StringUtils;
import net.alan.modules.aspect.NotAuthorize;
import net.alan.modules.bean.*;
import net.alan.modules.cache.WebContextUtil;
import net.alan.modules.handle.BaseExecption;
import net.alan.modules.service.INoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static net.alan.modules.bean.ResultUtil.success;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Api(tags = "个人笔记管理")
@Controller
@RequestMapping(value = "note")
public class NoteController extends BaseController {
    @Autowired
    private INoteService noteService;
    @Autowired
    private CustomConfig customConfig;

    @ApiOperation(value = "添加", notes = "")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public Result add(Integer id, String name, Integer catalogId, String content) throws Exception {
        try {

            Note note = this.noteService.getById(Note.class, id);
            if (note == null) {
                note = new Note();
                note.setUserId(WebContextUtil.getUserId());
            }
            String ctt = note.getContent();
            note.setName(name);
            note.setContent(content);
            note.setCatalogId(catalogId);
            noteService.saveNote(ctt, note);
        } catch (Exception baseExecption) {
            return ResultUtil.error("保存异常");
        }
        return success();
    }

    @ApiOperation(value = "添加目录", notes = "")
    @RequestMapping(value = "addcatalog", method = RequestMethod.POST)
    @ResponseBody
    public Result add(Integer id, String title) throws Exception {
        User user = WebContextUtil.getCurrentUser().getUser();
        try {
            NoteCatalog catalog = noteService.getById(NoteCatalog.class, id);
            if (catalog == null) {
                catalog = new NoteCatalog();
                catalog.setUserId(WebContextUtil.getUserId());
            }
            System.out.println(catalog.getTitle());
            catalog.setTitle(title);
            noteService.save(NoteCatalog.class, catalog);
        } catch (BaseExecption baseExecption) {
            baseExecption.printStackTrace();
            return ResultUtil.error("保存异常");
        }
        return success();
    }

    @ApiOperation(value = "修改", notes = "")
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    @ResponseBody
    public Result edit(Note note) throws Exception {
        User user = WebContextUtil.getCurrentUser().getUser();
        try {
            Note mynote = noteService.getById(Note.class, note.getId());
            mynote.setName(note.getName());
            mynote.setCatalogId(note.getCatalogId());
            mynote.setContent(note.getContent());
            noteService.save(Note.class, mynote);
        } catch (BaseExecption baseExecption) {
            return ResultUtil.error("保存异常");
        }
        return success();
    }

    @ApiOperation(value = "删除", notes = "")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer")
    @RequestMapping(value = "delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@PathVariable("id") Integer id) throws Exception {
        Result result = null;
        try {
            result = noteService.delete(Note.class, id);
        } catch (BaseExecption baseExecption) {
            result = ResultUtil.error("删除异常");
        }
        return result;
    }

    @ApiOperation(value = "删除目录", notes = "")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer")
    @RequestMapping(value = "deletecatalog/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteCatalog(@PathVariable("id") Integer id) throws Exception {
        return noteService.deleteCatalog(id);
    }

    @ApiOperation(value = "获取单个笔记", notes = "")
    @ApiImplicitParam(name = "id", value = "Id", required = true, dataType = "Integer")
    @RequestMapping(value = "get/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Note get(@PathVariable("id") Integer id) throws Exception {
        return noteService.getById(Note.class, id).copy();
    }

    @RequestMapping(value = "genshare/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Note genshare(@PathVariable("id") Integer id) throws Exception {
        Note note = noteService.getById(Note.class, id);
        if (StringUtils.isEmpty(note.getShareId())) {
            note.setShareId(UUID.randomUUID().toString());
            try {
                noteService.save(Note.class, note);
            } catch (BaseExecption baseExecption) {
                baseExecption.printStackTrace();
            }
        }
        return note.copy();
    }

    @NotAuthorize
    @RequestMapping(value = "getshare/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Note getshare(@PathVariable("id") String shareId) throws Exception {
        return noteService.getNoteByShareId(shareId).copy();
    }

    @ApiOperation(value = "获取单个历史笔记", notes = "")
    @ApiImplicitParam(name = "id", value = "Id", required = true, dataType = "Integer")
    @RequestMapping(value = "gethistory/{id}", method = RequestMethod.GET)
    @ResponseBody
    public NoteHistory gethistory(@PathVariable("id") Integer id) throws Exception {
        return noteService.getById(NoteHistory.class, id).copy();
    }

    @RequestMapping(value = "getcompare", method = RequestMethod.GET)
    @ResponseBody
    public List<Object> getcompare(Integer id1, Integer id2) throws Exception {
        List<Object> list = new ArrayList();
        Note note = this.noteService.getById(Note.class, id1);
        NoteHistory noteHistory = this.noteService.getById(NoteHistory.class, id2);
        list.add(noteHistory.copy());
        note = note.copy();
        note.setContent(CompareUtil.compare(noteHistory.getContent(), note.getContent()));
        list.add(note);
        return list;
    }

    @ApiOperation(value = "获取目录", notes = "")
    @ApiImplicitParam(name = "id", value = "Id", required = true, dataType = "Integer")
    @RequestMapping(value = "getcatalog/{id}", method = RequestMethod.GET)
    @ResponseBody
    public NoteCatalog getCatalog(@PathVariable("id") Integer id) throws Exception {
        return noteService.getById(NoteCatalog.class, id).copy();
    }

    @ApiOperation(value = "列表")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public PageModel list(Integer catalogId, PageModel pageModel) throws Exception {
        Page<Note> list = null;
        if (catalogId == null || catalogId <= 0)
            list = this.noteService.findNoteByUserId(WebContextUtil.getUserId(), pageModel);
        else
            list = this.noteService.findByNoteUserIdAndCatalogId(WebContextUtil.getUserId(), catalogId, pageModel);
        return pageModel.toPageModel(list);
    }

    @ApiOperation(value = "列表")
    @RequestMapping(value = "list/{id}", method = RequestMethod.GET)
    @ApiImplicitParam(name = "id", value = "Id", required = true, dataType = "Integer")
    @ResponseBody
    public PageModel listhistory(@PathVariable("id") Integer id, PageModel pageModel) throws Exception {
        Page<NoteHistory> list = null;
        list = this.noteService.findNoteHistoryByNoteId(WebContextUtil.getUserId(), id, pageModel);
        return pageModel.toPageModel(list);
    }

    @ApiOperation(value = "目录列表")
    @RequestMapping(value = "listcatalog", method = RequestMethod.GET)
    @ResponseBody
    public List<NoteCatalog> listCatalog() throws Exception {
        return noteService.findNoteCatalogByUserId(WebContextUtil.getUserId());
    }

    /**
     * 图片上传
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    public Result doUploadFile(HttpServletRequest request)
            throws Exception, IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        Result result = null;
        try {
            String postFix =
                    IOUtils.getPostFix(file.getOriginalFilename());
            String work = customConfig.getWorkPath();
            String fileName = System.currentTimeMillis() + "." + postFix;
            String filePath = work  + fileName;
            IOUtils.copyStream(file.getInputStream(), filePath);

            result = ResultUtil.success(new Src("../photo/image/" + Base64.encodeString(fileName)));
        } catch (Exception baseExecption) {
        }
        return result;
    }
}
